package com.zcaxer.way.fragments

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.viewModels
import com.google.android.material.textfield.TextInputEditText
import com.zcaxer.way.R
import com.zcaxer.way.data.Building
import com.zcaxer.way.viewmodels.BuildingViewModel
import java.util.zip.Inflater


class InputDialogFragment(val viewModel: BuildingViewModel, val building: Building, val type: String) : DialogFragment() {
    private lateinit var textInputEditText: TextInputEditText

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        textInputEditText = view.findViewById<TextInputEditText>(R.id.dialog_edit_text)
        textInputEditText.requestFocus();
        getDialog()!!.getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        val listener = TextView.OnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                textInputEditText.clearFocus()
                val imm = textInputEditText.context.getSystemService(Context.INPUT_METHOD_SERVICE)
                        as InputMethodManager
                imm.hideSoftInputFromWindow(textInputEditText.windowToken, 0)
            }
            false
        }
        textInputEditText.setOnEditorActionListener(listener)

    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        // final String result;
        val builder = AlertDialog.Builder(activity!!)
        builder.setView(R.layout.dialog_set_level_and_reserve).setTitle("请输入" + type)
        builder.setPositiveButton("确定") { dialog, _ ->
            textInputEditText = getDialog()!!.findViewById<TextInputEditText>(R.id.dialog_edit_text)
            val r: Int = textInputEditText.text.toString().toInt()
            viewModel.apply {
                when (type) {
                    getString(R.string.reserve) -> setBuildingReserve(building, r)
                    getString(R.string.workers) -> setBuildingWorkers(building, r)
                    getString(R.string.level) -> setLevel(building, r)
                }
            }
            dialog.cancel()
        }
        builder.setNegativeButton("取消") { dialog, _ -> dialog.cancel() }
        return builder.create()
    }

}
